package com.csdj.intercepter;

import com.csdj.service.RedisService;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginIntercepter implements HandlerInterceptor {

    @Resource
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取Cookie信息数组
        Cookie[] cks=request.getCookies();
        String uid="";//id
        String token="";//随机数
        if(cks!=null){
            for (Cookie cookie : cks) {
                //Cookie是以键值对的形式来保存数据的
                //可以通过键来获取相对应的值
                if("uid".equals(cookie.getName())){
                    uid=cookie.getValue();
                }
                if("token".equals(cookie.getName())){
                    token=cookie.getValue();
                }
            }
        }else{
            response.sendRedirect("tologin");
            return false;
        }
        if(redisService.hget("users",token+uid)!=null){
                /*if(redisService.getString().hget("users",token+uid)==token){
                    return true;
                }else {
                    response.sendRedirect("tologin");
                    return false;
                }*/
            return true;
        }else {
            response.sendRedirect("login");
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HttpSession session = request.getSession(false);
        boolean fold = false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


}
